package com.xjf.security.service;

import com.xjf.security.entity.InitData;
import com.xjf.security.entity.SysRole;
import com.xjf.security.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Spring Security 的 UserDetailsService 实现
 *
 * @author xjf
 * @date 2020/2/21 14:06
 */
@Service
public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟数据库查询
        SysUser sysUser = InitData.SYS_USERS.stream().filter(o -> StringUtils.equals(o.getUsername(), username)).findFirst().orElse(null);

        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 模拟从数据库获取权限
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        List<SysRole> roleList = sysUser.getRoles();
        roleList.forEach(o -> authorities.add(new SimpleGrantedAuthority(o.getRoleName())));

        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}
